﻿using System.Text.Json;
using System.Text.Json.Serialization;

namespace Lib.Serialization;
/// <summary>
/// 
/// </summary>
internal class DateTimeNullableConverter : JsonConverter<DateTime?> {
    /// <summary>
    /// 
    /// </summary>
    public override DateTime? Read(ref Utf8JsonReader Reader, Type TypeToConvert, JsonSerializerOptions Opts) {
        if (Reader.TokenType == JsonTokenType.String) {
            var Value = Reader.GetString();
            if (string.IsNullOrEmpty(Value)) {
                return default;
            } else {
                if (DateTime.TryParse(Value, out DateTime Date)) {
                    return Date;
                }
            }
        }
        return Reader.GetDateTime();
    }
    /// <summary>
    /// 
    /// </summary>
    public override void Write(Utf8JsonWriter Writer, DateTime? Value, JsonSerializerOptions Opts) {
        if (Value?.Hour == 0 && Value?.Minute == 0 && Value?.Second == 0) {
            Writer.WriteStringValue(Value?.ToString("yyyy-MM-dd"));
        } else {
            Writer.WriteStringValue(Value?.ToString("yyyy-MM-dd HH:mm:ss"));
        }
    }
}